package org.bogusware.json.builder;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonParser.Feature;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.resources.IResourceVisitor;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

public class JSONBuilder extends IncrementalProjectBuilder {

	class JSONResourceDeltaVisitor implements IResourceDeltaVisitor {
		
		public boolean visit(IResourceDelta delta) throws CoreException {
			IResource resource = delta.getResource();
			switch (delta.getKind()) {
			case IResourceDelta.ADDED:
				// handle added resource
				checkJSON(resource);
				break;
			case IResourceDelta.REMOVED:
				// handle removed resource
				break;
			case IResourceDelta.CHANGED:
				// handle changed resource
				checkJSON(resource);
				break;
			}
			//return true to continue visiting children.
			return true;
		}
	}

	class JSONResourceVisitor implements IResourceVisitor {
		public boolean visit(IResource resource) {
			try {
				checkJSON(resource);
			} catch (CoreException e) {
				throw new RuntimeException(e);
			}
			return true;
		}
	}

	public static final String BUILDER_ID = "json_creator.jsonBuilder";

	private static final String MARKER_TYPE = "json_creator.xmlProblem";

	private SAXParserFactory parserFactory;

	private void addMarker(IFile file, String message, int lineNumber,
			int severity) {
		try {
			IMarker marker = file.createMarker(MARKER_TYPE);
			marker.setAttribute(IMarker.MESSAGE, message);
			marker.setAttribute(IMarker.SEVERITY, severity);
			if (lineNumber == -1) {
				lineNumber = 1;
			}
			marker.setAttribute(IMarker.LINE_NUMBER, lineNumber);
		} catch (CoreException e) {
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.core.internal.events.InternalBuilder#build(int,
	 *      java.util.Map, org.eclipse.core.runtime.IProgressMonitor)
	 */
	protected IProject[] build(int kind, Map args, IProgressMonitor monitor)
			throws CoreException {
		if (kind == FULL_BUILD) {
			fullBuild(monitor);
		} else {
			IResourceDelta delta = getDelta(getProject());
			if (delta == null) {
				fullBuild(monitor);
			} else {
				incrementalBuild(delta, monitor);
			}
		}
		return null;
	}

	void checkJSON(IResource resource) throws CoreException {
		if (resource instanceof IFile && resource.getName().endsWith(".json")) {
			IFile file = (IFile) resource;
			deleteMarkers(file);
			JsonFactory jsonFactory = new JsonFactory();
			try {
				InputStream fileContent = file.getContents();
				JsonParser parser = jsonFactory.createJsonParser(fileContent);
				parser.configure(Feature.ALLOW_COMMENTS, true);
				parser.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
				while (parser.nextToken() != null);
				fileContent.close();
			} catch (JsonParseException e) {
				addMarker(file, e.getMessage(), 0, IMarker.SEVERITY_ERROR);
			} catch (IOException e) {
				throw new RuntimeException(e);
			} 
		}
	}

	private void deleteMarkers(IFile file) {
		try {
			file.deleteMarkers(MARKER_TYPE, false, IResource.DEPTH_ZERO);
		} catch (CoreException ce) {
		}
	}

	protected void fullBuild(final IProgressMonitor monitor)
			throws CoreException {
		try {
			getProject().accept(new JSONResourceVisitor());
		} catch (CoreException e) {
		}
	}

	protected void incrementalBuild(IResourceDelta delta,
			IProgressMonitor monitor) throws CoreException {
		// the visitor does the work.
		delta.accept(new JSONResourceDeltaVisitor());
	}
}
